package com.xiejun.netty;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SimpleNettyServer {
    
    private final int port;
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    
    public SimpleNettyServer(int port) {
        this.port = port;
    }
    
    public void start() throws IOException {
        // 打开选择器
        selector = Selector.open();
        
        // 打开服务器套接字通道
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        
        // 绑定端口
        serverSocketChannel.bind(new InetSocketAddress(port));
        
        // 注册接受连接事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        
        System.out.println("Simple Netty Server started on port " + port);
        
        // 事件循环
        while (true) {
            // 等待事件
            selector.select();
            
            // 处理事件
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
            
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                
                if (key.isAcceptable()) {
                    handleAccept(key);
                } else if (key.isReadable()) {
                    handleRead(key);
                }
                
                keyIterator.remove();
            }
        }
    }
    
    private void handleAccept(SelectionKey key) throws IOException {
        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
        SocketChannel clientChannel = serverChannel.accept();
        clientChannel.configureBlocking(false);
        
        System.out.println("Client connected: " + clientChannel.getRemoteAddress());
        
        // 注册读事件
        clientChannel.register(selector, SelectionKey.OP_READ);
    }
    
    private void handleRead(SelectionKey key) throws IOException {
        SocketChannel clientChannel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        
        int bytesRead = clientChannel.read(buffer);
        if (bytesRead == -1) {
            // 客户端关闭连接
            System.out.println("Client disconnected: " + clientChannel.getRemoteAddress());
            clientChannel.close();
            return;
        }
        
        // 处理读取到的数据
        buffer.flip();
        byte[] data = new byte[buffer.remaining()];
        buffer.get(data);
        String message = new String(data);
        
        System.out.println("Received from " + clientChannel.getRemoteAddress() + ": " + message);
        
        // 回写数据
        String response = "Echo: " + message;
        ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());
        clientChannel.write(responseBuffer);
    }
    
    public static void main(String[] args) {
        try {
            new SimpleNettyServer(8080).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}